<?php

$db = DB::getInstance();

$group = Request::post("group");

$result = array();
if($group) {
	try {
		$result = $db->query("select * from gc_group where name = ?", array($group));
		if(count($result['rows']) > 0) {
			$key = Request::post("key");
			$value = Request::post("value", '', true);
			$val_type = Request::post("val_type");

			if(!$key || !$value) {
				throw new Exception ("Key or value cann't be empty");
			}
			$key = Request::filter($key);

			try {
				$db->begin();
				$sql = "INSERT INTO gc_config (`group_name`, `key`, `value`, `val_type`, `version`) ";
				$sql .= "VALUES(?, ?, ?, ?, ?) ";
				$sql .= "ON DUPLICATE KEY UPDATE `value` = ?, `val_type` = ?, `version` = `version` + 1";
				$result = $db->query($sql, array($group, $key, $value, $val_type, C::VERSION_INIT, $value, $val_type));

				if($result['affected_rows'] > 0) {
					$sql = "select * from gc_config where `group_name` = ? and `key` = ?";
					$result = $db->query($sql, array($group, $key));

					$row = $result['rows'][0];
					$sql = "insert into gc_config_history (`group_name`, `key`, `val_type`, `version`, `value`) ";
					$sql .= "values (?, ?, ?, ?, ?)";
					$r = $db->query($sql, array($row['group_name'], $row['key'], $row['val_type'], $row['version'], $row['value']));

					foreach($result['rows'] as &$r) {
						$r['val_type'] = C::getTypeText($r['val_type']);	
					}
					unset($r);
				}
				$db->commit();
			} catch(Exception $e) {
				$db->rollback();
				throw $e;
			}
		} else {
			$result['msg'] = "'$group' does not exist!";	
		}
	} catch (Exception $e) {
		$result['msg'] = $e->getMessage();	
	}
}

return $result;

